<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <el-card class="search-card">
      <el-form :model="filterForm" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="公司名称">
              <el-input v-model="filterForm.companyName" placeholder="输入公司名称" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="品牌">
              <el-input v-model="filterForm.brand" placeholder="输入品牌" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="状态">
              <el-select v-model="filterForm.isActive" placeholder="选择状态" clearable style="width: 100%">
                <el-option label="全部" value="" />
                <el-option label="启用" :value="0" />
                <el-option label="禁用" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="3" class="text-left">
            <el-button type="primary" @click="handleQuery">
              查询
            </el-button>
            <el-button @click="handleReset">
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="mt-1">
      <!-- 操作按钮 -->
      <div class="mb-2">
        <el-button type="primary" @click="handleAdd">
          新增供应商
        </el-button>
        <el-button :disabled="!selectedRows.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>

      <!-- 设备供应商表格 -->
      <el-table :data="supplierList" border style="width: 100%" v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="companyName" label="公司名称" align="center" />
        <el-table-column prop="brand" label="品牌" align="center" />
        <el-table-column prop="contactPerson" label="联系人" align="center" />
        <el-table-column prop="contactNumber" label="联系电话" align="center" />
        <el-table-column prop="email" label="电子邮箱" align="center" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive === 0 ? 'success' : 'danger'">
              {{ row.isActive === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registrationDate" label="注册日期" align="center" width="180" />
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleDetail(row.supplierId)">
              详情
            </el-button>
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleDelete(row.supplierId)" style="color: #f56c6c">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑设备供应商对话框 -->
    <el-dialog :title="formType === 'add' ? '新增设备供应商' : '编辑设备供应商'" v-model="formVisible" width="700px"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="formData.companyName" placeholder="输入公司名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="formData.brand" placeholder="输入品牌" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="输入联系人姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="formData.contactNumber" placeholder="输入联系电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电子邮箱">
              <el-input v-model="formData.email" placeholder="输入电子邮箱" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="formData.isActive" placeholder="选择状态" style="width: 100%">
                <el-option label="启用" :value="0" />
                <el-option label="禁用" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="联系地址">
          <el-input v-model="formData.address" placeholder="输入联系地址" clearable />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业执照编号">
              <el-input v-model="formData.businessLicenseNumber" placeholder="输入营业执照编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册日期">
              <el-date-picker v-model="formData.registrationDate" type="date" placeholder="选择注册日期"
                value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备供应商详情对话框 -->
    <el-dialog title="设备供应商详情" v-model="detailVisible" width="800px" top="5vh" :close-on-click-modal="false">
      <el-descriptions border :column="2">
        <el-descriptions-item label="公司名称">{{ currentDetail.companyName }}</el-descriptions-item>
        <el-descriptions-item label="品牌">{{ currentDetail.brand }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ currentDetail.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentDetail.contactNumber }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ currentDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentDetail.isActive === 0 ? 'success' : 'danger'">
            {{ currentDetail.isActive === 0 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系地址">{{ currentDetail.address }}</el-descriptions-item>
        <el-descriptions-item label="营业执照编号">{{ currentDetail.businessLicenseNumber }}</el-descriptions-item>
        <el-descriptions-item label="注册日期">{{ currentDetail.registrationDate }}</el-descriptions-item>
        <el-descriptions-item label="信用评级">{{ currentDetail.creditRating }}</el-descriptions-item>
        <el-descriptions-item label="上次订单日期">{{ currentDetail.lastOrderDate }}</el-descriptions-item>
        <el-descriptions-item label="累计订单金额">{{ currentDetail.totalOrderAmount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ currentDetail.remark }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listEquipmentSupplier,
  getEquipmentSupplier,
  addEquipmentSupplier,
  updateEquipmentSupplier,
  deleteEquipmentSupplier
} from '@/api/prod_operate/synthesis/provide/device_sup'

// 数据状态
const loading = ref(false)
const formVisible = ref(false)
const detailVisible = ref(false)
const formType = ref('add') // 'add' or 'edit'
const selectedRows = ref([])

// 筛选表单
const filterForm = reactive({
  companyName: '',
  brand: '',
  isActive: '',
  dateRange: []
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  supplierId: null,
  companyName: '',
  brand: '',
  contactPerson: '',
  contactNumber: '',
  email: '',
  address: '',
  businessLicenseNumber: '',
  registrationDate: '',
  isActive: 0,
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
})

// 详情数据
const currentDetail = ref({})

// 设备供应商列表数据
const supplierList = ref([])

// 获取设备供应商列表
const fetchSupplierList = async () => {
  try {
    loading.value = true
    const params = {
      companyName: filterForm.companyName,
      brand: filterForm.brand,
      isActive: filterForm.isActive,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    if (filterForm.dateRange?.length === 2) {
      params.startTime = filterForm.dateRange[0]
      params.endTime = filterForm.dateRange[1]
    }

    const res = await listEquipmentSupplier(params)
    supplierList.value = res.rows || []
    pagination.total = res.total || 0
  } catch (error) {
    console.error('获取设备供应商列表失败:', error)
    ElMessage.error('获取设备供应商列表失败')
  } finally {
    loading.value = false
  }
}

// 获取设备供应商详情
const fetchSupplierDetail = async (supplierId) => {
  try {
    const res = await getEquipmentSupplier(supplierId)
    currentDetail.value = res.data || {}
  } catch (error) {
    console.error('获取设备供应商详情失败:', error)
    ElMessage.error('获取设备供应商详情失败')
  }
}

// 查询处理
const handleQuery = () => {
  pagination.currentPage = 1
  fetchSupplierList()
}

// 重置查询
const handleReset = () => {
  Object.assign(filterForm, {
    companyName: '',
    brand: '',
    isActive: '',
    dateRange: []
  })
  handleQuery()
}

// 新增设备供应商
const handleAdd = () => {
  formType.value = 'add'
  Object.assign(formData, {
    supplierId: null,
    companyName: '',
    brand: '',
    contactPerson: '',
    contactNumber: '',
    email: '',
    address: '',
    businessLicenseNumber: '',
    registrationDate: '',
    isActive: 0,
    remark: ''
  })
  formVisible.value = true
}

// 编辑设备供应商
const handleEdit = (row) => {
  formType.value = 'edit'
  Object.assign(formData, {
    supplierId: row.supplierId,
    companyName: row.companyName,
    brand: row.brand,
    contactPerson: row.contactPerson,
    contactNumber: row.contactNumber,
    email: row.email,
    address: row.address,
    businessLicenseNumber: row.businessLicenseNumber,
    registrationDate: row.registrationDate,
    isActive: row.isActive,
    remark: row.remark
  })
  formVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    if (formType.value === 'add') {
      await addEquipmentSupplier(formData)
      ElMessage.success('新增设备供应商成功')
    } else {
      await updateEquipmentSupplier(formData)
      ElMessage.success('修改设备供应商成功')
    }
    formVisible.value = false
    fetchSupplierList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 查看详情
const handleDetail = async (supplierId) => {
  await fetchSupplierDetail(supplierId)
  detailVisible.value = true
}

// 删除设备供应商
const handleDelete = (supplierId) => {
  ElMessageBox.confirm('确定要删除该设备供应商吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteEquipmentSupplier(supplierId)
      ElMessage.success('删除成功')
      fetchSupplierList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  const supplierIds = selectedRows.value.map(item => item.supplierId).join(',')

  ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteEquipmentSupplier(supplierIds)
      ElMessage.success('批量删除成功')
      selectedRows.value = []
      fetchSupplierList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => { })
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchSupplierList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchSupplierList()
}

// 初始化数据
onMounted(() => {
  fetchSupplierList()
})
</script>

<style scoped>
.filter-form {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.mb-2 {
  margin-bottom: 20px;
}

.highlight-text {
  color: #409EFF;
  font-weight: bold;
}


.search-card :deep(.el-form-item) , .search-card  :deep(.el-form) {
  margin-bottom: 0px;
}
</style>